const jwt = require('jsonwebtoken');
const returnDataFormat = require('../common/returnDataFormat');
const jwtSecret = 'Dpl_jwt_Secret';

let setToken = function (username, userId, userLevel, state) {
  return new Promise((resolve, reject) => {
    const token = jwt.sign({ username, userId, userLevel, state }, jwtSecret, {
      expiresIn: '24h',
    });
    resolve(token);
  });
};

let verifyToken = function (token) {
  return new Promise((resolve, reject) => {
    if (!token) {
      reject(returnDataFormat.SimpleData(500, 'token为空'));
    } else {
      jwt.verify(token, jwtSecret, function (err, data) {
        if (err) {
          reject(returnDataFormat.SimpleData(500, 'token错误或已失效'));
        } else {
          resolve(returnDataFormat.SQLData(null, data, 'token验证通过'));
        }
      });
    }
  });
};

module.exports = {
  setToken,
  verifyToken,
};
